package net.maku.kyy.controller;

import cn.hutool.core.util.RandomUtil;
import lombok.extern.slf4j.Slf4j;
import net.maku.api.module.system.SmsApi;
import net.maku.framework.common.utils.Result;
import net.maku.kyy.dto.KyySignDTO;
import net.maku.kyy.dto.KyyUserRegisterDTO;
import net.maku.kyy.service.KyyUserRegisterService;
import net.maku.tencentsms.service.TencentSmsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.*;

import java.util.concurrent.TimeUnit;

/**
 * 注册
 */
@Slf4j
@RestController
@RequestMapping("/kyy/register")
@Component
public class KyyUserRegisterController {
    @Autowired
    private KyyUserRegisterService kyyUserRegisterService;

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @Autowired
    private TencentSmsService smsApi;
    

    /**
     * 注册
     * @param kyySignDTO
     */
    @PostMapping
    public Result register(@RequestBody KyySignDTO kyySignDTO) {
        System.out.println("kyysigndto"+kyySignDTO);
        KyyUserRegisterDTO kyyUserRegisterDTO = kyySignDTO.getKyyUserRegisterDTO();
        log.info("用户注册：{}",kyyUserRegisterDTO);
        kyyUserRegisterService.register(kyySignDTO);
        return Result.ok();
    }

    /**
     * 发送注册验证码
     * @param phone 手机号
     * @return
     */
    @PostMapping("/sendcode/{phone}")
    public Result sendCode(@PathVariable("phone")String phone) {
        log.info("发送注册验证码，手机号：{}", phone);
        
        // 生成6位数字验证码
        String code = RandomUtil.randomNumbers(6);

        try {
            System.out.println(redisTemplate);
            redisTemplate.opsForValue().set("kyy:register:code:" + phone, code, 5, TimeUnit.MINUTES);
            System.out.println("Redis连接测试成功，获取的值: ");
            smsApi.sendSms(phone, new String[]{code});
        } catch (Exception e) {
            System.err.println("Redis连接失败: " + e.getMessage());
        }
        System.out.println("验证码发送成功，验证码：" + code);
        return Result.ok();
    }
}
